﻿using PLC.Interface.Stations;
using PLC.Interface.StationVariables;
using PLCWpfTest.Common;
using PLCWpfTest.Common.Extensions;
using PLCWpfTest.Models;
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using YWM;
using YWM.Common.Exceptions;
using YWM.Localization;

namespace PLCWpfTest.Controls
{
    /// <summary>
    /// StationDisplay.xaml 的交互逻辑
    /// </summary>
    public partial class StationDisplay : UserControl
    {
        private event Action<ParameterModel> _variableDoubleClick;
        public event Action<ParameterModel> VariableDoubleClick
        {
            add { _variableDoubleClick += value; }
            remove { _variableDoubleClick -= value; }
        }

        private static readonly DependencyProperty StationProperty = DependencyProperty.Register(nameof(Station), typeof(StationResultDto), typeof(StationDisplay), new PropertyMetadata(new StationResultDto(), null, StationCoerceValueCallback));

        [Bindable(true), Category("自定义属性"), Description("站点对象")]
        public StationResultDto Station
        {
            get { return (StationResultDto)GetValue(StationProperty); }
            set { SetValue(StationProperty, value); }
        }

        public StationDisplay()
        {
            InitializeComponent();
        }

        private static object StationCoerceValueCallback(DependencyObject d, object baseValue)
        {
            if (baseValue == null)
            {
                return baseValue;
            }

            StationResultDto station = (StationResultDto)baseValue;
            StationVariableResultDto stationVariable = station.StationVariable;
            StationDisplay stationDisplay = (StationDisplay)d;
            ILocalizationManager lang = YApp.Resolve<ILocalizationManager>();
            string title = lang == null ? "" : string.Format(lang["站点"], station.Identifier);
            stationDisplay.StationTitle.Title = title;
            if (station.StationVariable != null)
            {
                stationDisplay.TempHighVD.LimitNameTB.Text = $"{title}{lang["温度高限"]}";
                stationDisplay.TempHighVD.LimitValueTB.Text = stationVariable.TempHighLimitValue.ToString();
                stationDisplay.TempHighVD.StatusCS.Status = !stationVariable.TempHighValue;

                stationDisplay.TempLowVD.LimitNameTB.Text = $"{title}{lang["温度低限"]}";
                stationDisplay.TempLowVD.LimitValueTB.Text = stationVariable.TempLowLimitValue.ToString();
                stationDisplay.TempLowVD.StatusCS.Status = !stationVariable.TempLowValue;

                stationDisplay.HumidityHighVD.LimitNameTB.Text = $"{title}{lang["湿度高限"]}";
                stationDisplay.HumidityHighVD.LimitValueTB.Text = stationVariable.HumidityHighLimitValue.ToString();
                stationDisplay.HumidityHighVD.StatusCS.Status = !stationVariable.HumidityHighValue;

                stationDisplay.HumidityLowVD.LimitNameTB.Text = $"{title}{lang["湿度低限"]}";
                stationDisplay.HumidityLowVD.LimitValueTB.Text = stationVariable.HumidityLowLimitValue.ToString();
                stationDisplay.HumidityLowVD.StatusCS.Status = !stationVariable.HumidityLowValue;

                stationDisplay.TempAlarmEnableName.Checked -= stationDisplay.TempAlarmEnableName_CheckedOrUnchecked;
                stationDisplay.TempAlarmEnableName.Unchecked -= stationDisplay.TempAlarmEnableName_CheckedOrUnchecked;
                stationDisplay.TempAlarmEnableName.IsChecked = stationVariable.TempAlarmEnableValue == 1;
                stationDisplay.TempAlarmEnableName.Checked += stationDisplay.TempAlarmEnableName_CheckedOrUnchecked;
                stationDisplay.TempAlarmEnableName.Unchecked += stationDisplay.TempAlarmEnableName_CheckedOrUnchecked;

                stationDisplay.HumidityAlarmEnableName.Checked -= stationDisplay.HumidityAlarmEnableName_CheckedOrUnchecked;
                stationDisplay.HumidityAlarmEnableName.Unchecked -= stationDisplay.HumidityAlarmEnableName_CheckedOrUnchecked;
                stationDisplay.HumidityAlarmEnableName.IsChecked = stationVariable.HumidityAlarmEnableValue == 1;
                stationDisplay.HumidityAlarmEnableName.Checked += stationDisplay.HumidityAlarmEnableName_CheckedOrUnchecked;
                stationDisplay.HumidityAlarmEnableName.Unchecked += stationDisplay.HumidityAlarmEnableName_CheckedOrUnchecked;
            }
            return station;
        }

        private void TempHighVD_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ParameterModel parameter = new ParameterModel
            {
                Id = Station.StationVariable.TempHighLimitId,
                Name = TempHighVD.LimitNameTB.Text,
                Value = Station.StationVariable.TempHighLimitValue,
                WaringText = string.Format(YApp.Resolve<ILocalizationManager>()["温度低限不能高于温度高限"], Station.Identifier),
                CompareValue = Station.StationVariable.TempLowLimitValue,

                IsHigh = true,
            };
            Execute(parameter);
        }

        private void TempLowVD_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ParameterModel parameter = new ParameterModel
            {
                Id = Station.StationVariable.TempLowLimitId,
                Name = TempLowVD.LimitNameTB.Text,
                Value = Station.StationVariable.TempLowLimitValue,
                WaringText = string.Format(YApp.Resolve<ILocalizationManager>()["温度低限不能高于温度高限"], Station.Identifier),
                CompareValue = Station.StationVariable.TempHighLimitValue,
            };
            Execute(parameter);
        }

        private void HumidityHighVD_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ParameterModel parameter = new ParameterModel
            {
                Id = Station.StationVariable.HumidityHighLimitId,
                Name = HumidityHighVD.LimitNameTB.Text,
                Value = Station.StationVariable.HumidityHighLimitValue,
                WaringText = string.Format(YApp.Resolve<ILocalizationManager>()["湿度低限不能高于湿度高限"], Station.Identifier),
                CompareValue = Station.StationVariable.HumidityLowLimitValue,
                IsHigh = true,
            };
            Execute(parameter);
        }

        private void HumidityLowVD_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ParameterModel parameter = new ParameterModel
            {
                Id = Station.StationVariable.HumidityLowLimitId,
                Name = HumidityLowVD.LimitNameTB.Text,
                Value = Station.StationVariable.HumidityLowLimitValue,
                WaringText = string.Format(YApp.Resolve<ILocalizationManager>()["湿度低限不能高于湿度高限"], Station.Identifier),
                CompareValue = Station.StationVariable.HumidityHighLimitValue,
            };
            Execute(parameter);
        }

        private void Execute(ParameterModel parameter)
        {
            _variableDoubleClick?.Invoke(parameter);
        }

        private async void TempAlarmEnableName_CheckedOrUnchecked(object sender, RoutedEventArgs e)
        {
            await UpdateParameter(Station.StationVariable.TempAlarmEnableId, TempAlarmEnableName.IsChecked == true ? "1" : "0");
        }

        private async void HumidityAlarmEnableName_CheckedOrUnchecked(object sender, RoutedEventArgs e)
        {
            await UpdateParameter(Station.StationVariable.HumidityAlarmEnableId, HumidityAlarmEnableName.IsChecked == true ? "1" : "0");
        }

        private async Task UpdateParameter(long id, string set)
        {
            if (!CommunicationCache.Connected)
            {
                this.ShowWarning("通信设备连接失败");
                return;
            }
            try
            {
                await CommunicationCache.UpdateParameter(id, set);
            }
            catch (FriendlyException ex)
            {
                this.ShowError(ex.Message);
            }
        }
    }
}
